package org.sshbot;

import java.io.Writer;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.ResultReceiver;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.sshbot.GestureListener;
import org.sshbot.TouchListener;
import org.sshbot.transport.PromptMessage;
import org.sshbot.transport.Transport;

import com.securecrt.SaveSession;

import static org.sshbot.util.LogHelper.DEBUG;

/**
 * User: parkerkane
 * Date: 13.12.2010
 * Time: 9:54
 */
public class TerminalView extends BaseTerminalView {

	private boolean isSoftKeyVisible = false;
	private boolean checkSoftKey     = false;
	private ImageView mKeyboardButton;
	private final static int FONT_SIZE_STEP = 2;
	
	Handler  softKeyCheckHandler = new Handler();
	Runnable softKeyCheckRunner  = new Runnable() {

		public void run() {

			Handler handle = new Handler();

			ResultReceiver rr = new ResultReceiver(handle) {

				@Override
				protected void onReceiveResult(int resultCode, Bundle resultData) {
					if (resultCode == InputMethodManager.RESULT_SHOWN) {
						checkSoftKey = false;
						inputManager.hideSoftInputFromWindow(getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
					}

					super.onReceiveResult(resultCode, resultData);

					boolean oldVis = isSoftKeyVisible;

					isSoftKeyVisible = resultCode == InputMethodManager.RESULT_UNCHANGED_SHOWN;

					if (oldVis != isSoftKeyVisible) {
						resizeScreen();
					}
				}
			};

			if (checkSoftKey) {
				inputManager.showSoftInput(TerminalView.this, InputMethodManager.SHOW_IMPLICIT, rr);
			}
			
			softKeyCheckHandler.postDelayed(this, 1000);
		}
	};

	private void startTimer() {

		this.halt();
		softKeyCheckHandler.postDelayed(softKeyCheckRunner, 1000);
	}

	public void resume() {

		this.startTimer();
	}

	public void halt() {

		softKeyCheckHandler.removeCallbacks(softKeyCheckRunner);
	}

	public TerminalView(Context context, final Transport transport) {

		super(context, transport);

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.MATCH_PARENT;
		setLayoutParams(lp);

		transport.setPromptHandler(new PromptHandler());

		transport.connect();

		setFocusable(true);
		setFocusableInTouchMode(true);
		
		
		
//		setFontSize(22);
		setOnKeyListener(new TerminalKeyListener(this, transport, buffer));

		requestFocus();

		setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
//				inputManager.showSoftInput(TerminalView.this, InputMethodManager.SHOW_FORCED);
				inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
				checkSoftKey = true;
				isSoftKeyVisible = true;
				
				resizeScreen();
			}
		});
		final GestureDetector detect = new GestureDetector(new GestureListener(this));
		setOnTouchListener(new TouchListener(detect));	
	}

	public void resizeScreen() {
		DEBUG("Is soft key visible?", isSoftKeyVisible);

		this.onSizeChanged(getWidth(), getHeight(), getWidth(), getHeight());
	}

	public void increaseFontSize() {
		    setFontSize(fontSize + FONT_SIZE_STEP);
		    resetScrollPosition();
		    resizeScreen();
	}

	public void decreaseFontSize() {
		    setFontSize(fontSize - FONT_SIZE_STEP);
		    resetScrollPosition();
		    resizeScreen();
	}
		  
	@Override
	protected void onSizeChanged(int width, int height, int oldw, int oldh) {

		// TODO Needs user configured height for portrait and landscape
		
//		if (isSoftKeyVisible) {
//			if (MainActivity.isPortrait) {
//				height = 30 * charHeight;
//			} else {
//				height = 15 * charHeight;
//			}
//		}
		if (isSoftKeyVisible) {
			if (SaveSession.isPortrait) {
				height = 20 * charHeight;
			} else {
				height = 9 * charHeight;
			}
		}

		super.onSizeChanged(width, height, oldw, oldh);
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		
		checkSoftKey = true;

		startTimer();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();

		halt();
	}
	
	@Override
    public boolean onCheckIsTextEditor() {
            return true;
    }
	
	 @Override
     public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
             outAttrs.imeOptions |=
                     EditorInfo.IME_FLAG_NO_EXTRACT_UI |
                     EditorInfo.IME_FLAG_NO_ENTER_ACTION |
                     EditorInfo.IME_ACTION_NONE;
             outAttrs.inputType = EditorInfo.TYPE_NULL;
             return new BaseInputConnection(this, false) {
                     @Override
                     public boolean deleteSurroundingText (int leftLength, int rightLength) {
                             if (rightLength == 0 && leftLength == 0) {
                                     return this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
                             }
                             for (int i = 0; i < leftLength; i++) {
                                     this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
                             }
                             // TODO: forward delete
                             return true;
                     }
             };
     }

	private class PromptHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			final PromptMessage data = (PromptMessage) msg.obj;

			DEBUG("Got prompt message:", data.type);
			
			switch (data.type) {
				case Message:
					Toast.makeText(TerminalView.this.context, data.message, Toast.LENGTH_LONG).show();
					data.release();
					break;

				case Boolean:

					final Dialog dialog4=new Dialog(TerminalView.this.context);
					dialog4.requestWindowFeature(Window.FEATURE_NO_TITLE);
					dialog4.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
					Context mContext=TerminalView.this.context.getApplicationContext();
					LayoutInflater inflater=(LayoutInflater) mContext.getSystemService(TerminalView.this.context.LAYOUT_INFLATER_SERVICE);
					View layout=inflater.inflate(R.layout.confirmssh, (ViewGroup) findViewById(R.id.confirmssh));
					dialog4.setContentView(layout);
					final Button btok=(Button)layout.findViewById(R.id.btok);
					btok.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
					btok.setOnClickListener(new Button.OnClickListener() {
						@Override
						public void onClick(View v) {
							data.sendResponse(true);
							dialog4.dismiss();
						}
					});
					final Button btcancel=(Button)layout.findViewById(R.id.btcancel);
					btcancel.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
					btcancel.setOnClickListener(new Button.OnClickListener() {			
						@Override
						public void onClick(View v) {
							data.sendResponse(false);
							System.exit(0);
						}
					});
					dialog4.show();

					break;

				case String:
					data.release();
					break;

				case Password:
					
					final Dialog dialog = new Dialog(TerminalView.this.context);

					dialog.setTitle(data.message);
					dialog.setContentView(R.layout.password);
					dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

					final EditText password = (EditText) dialog.findViewById(R.id.password);					
					final Button click = (Button) dialog.findViewById(R.id.click);

					password.setText("");
					InputMethodManager mgr = (InputMethodManager) TerminalView.this.context.getSystemService(Context.INPUT_METHOD_SERVICE);
					mgr.showSoftInput(TerminalView.this.findFocus(), InputMethodManager.SHOW_FORCED);
					password.requestFocus();
					password.setOnKeyListener(new OnKeyListener() {

						public boolean onKey(View v, int keyCode, KeyEvent event) {

							if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
								data.sendResponse(password.getText().toString());
								hideKeyBoard(password);
								dialog.dismiss();
								return true;
							}

							return false;
						}
					});
					click.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							data.sendResponse(password.getText().toString());
							hideKeyBoard(password);
							dialog.dismiss();
						}
					});

					dialog.show();
					break;

			}
		}
	}
	private void hideKeyBoard(EditText password){
		InputMethodManager mgr = (InputMethodManager) TerminalView.this.context.getSystemService(Context.INPUT_METHOD_SERVICE);
		mgr.hideSoftInputFromWindow(password.getWindowToken(), 0);
	}
	
}
